package com.video.tiktokdownloader.nowatermark

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.PopupWindow
import androidx.cardview.widget.CardView
import com.bumptech.glide.Glide
import com.google.ads.mediation.facebook.FacebookAdapter
import com.google.ads.mediation.facebook.FacebookExtras
import com.google.android.ads.nativetemplates.NativeTemplateStyle
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdLoader
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.formats.NativeAdOptions
import com.google.android.gms.ads.formats.UnifiedNativeAd
import com.video.tiktokdownloader.nowatermark.HomeActivity.Companion.getAdRequest
import com.video.tiktokdownloader.nowatermark.bean.MediaEntity
import kotlinx.android.synthetic.main.fragment_home.*


/**
 * @author Afra55
 * @date 2020/6/26
 * A smile is the best business card.
 */
class HomeFragment :BaseFragment(){

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }
    lateinit var adLoader: AdLoader
    val handler = Handler(Handler.Callback {
        try {
            if (!myActivity.isFinishing) {
                adLoader.loadAd(AdRequest.Builder().build())

            }
        } catch (e: Exception) {
        }
        false
    })
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        home_download_btn.setOnClickListener {
            val text = home_link_edit.text.toString()
            if (text.isNotEmpty()) {

                showPopupWindow(home_download_btn)
            }
        }

        home_setting.setOnClickListener {

            startActivity(Intent(myActivity, SettingActivity::class.java))
        }

//        initAd()
    }

    private fun initAd() {
        adLoader = AdLoader.Builder(myActivity, getString(R.string.admob_native_id))
            .forUnifiedNativeAd { ad: UnifiedNativeAd ->
                // Show the ad.
                try {
                    if (adLoader.isLoading) {
                        // The AdLoader is still loading ads.
                        // Expect more adLoaded or onAdFailedToLoad callbacks.
                    } else {
                        // The AdLoader has finished loading ads.
                        val styles =
                            NativeTemplateStyle.Builder()
                                .withMainBackgroundColor(ColorDrawable(resources.getColor(R.color.bg_color)))
                                .build()

                        my_template.setStyles(styles)
                        my_template.setNativeAd(ad)
                        handler.sendEmptyMessageDelayed(0, 5000)
                    }
                } catch (e: Exception) {
                }
            }
            .withAdListener(object : AdListener() {
                override fun onAdFailedToLoad(errorCode: Int) {
                    // Handle the failure by logging, altering the UI, and so on.
                }
            })
            .withNativeAdOptions(
                NativeAdOptions.Builder()
                    // Methods in the NativeAdOptions.Builder class can be
                    // used here to specify individual options settings.
                    .build()
            )
            .build()
        var extras = FacebookExtras()
            .setNativeBanner(true)
            .build()
        adLoader.loadAd(getAdRequest())
    }

    val presenter by lazy {
        ApiPresenter(myActivity, object :Listener{
            override fun onView(type: Int, any: Any?) {

                if (type == 1) {
                    try {
                        if (any is MediaEntity) {
                            context?.let { Glide.with(it).load(any.cover).into(home_f_image) }
                        }
                    } catch (e: Exception) {
                    }
                }
            }
        })
    }

    var downloadPopupWindow: PopupWindow? = null

    fun showPopupWindow(view:View) {
        if (downloadPopupWindow == null) {
            val layout = View.inflate(context, R.layout.pop_download_layout, null)
            downloadPopupWindow = PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            // 设置背景
            // 设置背景
            downloadPopupWindow!!.setBackgroundDrawable(ColorDrawable())
            // 外部点击事件
            // 外部点击事件
            downloadPopupWindow!!.isOutsideTouchable = true

            layout.findViewById<View>(R.id.pop_download_video).setOnClickListener {
                val text = home_link_edit.text.toString()
                if (text.isNotEmpty()) {

                    presenter.doAction(text, 0 )
                }
                downloadPopupWindow?.dismiss()
            }
            layout.findViewById<View>(R.id.pop_download_music).setOnClickListener {
                val text = home_link_edit.text.toString()
                if (text.isNotEmpty()) {

                    presenter.doAction(text, 1 )
                }
                downloadPopupWindow?.dismiss()
            }
        }

        downloadPopupWindow?.showAsDropDown(view, 0, 0, Gravity.CENTER_HORIZONTAL)
    }

    override fun onResume() {
        super.onResume()
        activity?.window?.decorView?.post {
            val cm =
                context?.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
            val clip = cm?.primaryClip
            var text1: CharSequence? = null
            if (clip != null && clip.itemCount > 0) {
                text1 = clip.getItemAt(0).coerceToText(getContext())
            }
            if (!text1.isNullOrEmpty()) {
                if (text1.startsWith("https://vm.tiktok.com") || text1.startsWith("https://www.tiktok.com/@")) {

                    home_link_edit.setText(text1)
                    val cm =
                        myActivity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    cm.setPrimaryClip(ClipData.newPlainText("copy", ""))
                }
            }



        }
    }
}


class SquareFrameLayout : FrameLayout {
    constructor(context: Context?) : super((context)!!) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(
        (context)!!,
        attrs
    ) {
    }

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) : super((context)!!, attrs, defStyleAttr) {
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int): Unit {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec)
    }
}


class SquareCardView : CardView {
    constructor(context: Context) : super(context) {}
    constructor(context: Context, attrs: AttributeSet?) : super(
        context,
        attrs
    ) {
    }

    constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr) {
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec)
    }
}
